<!-- 新增 -->
<template>
  <!-- 新增 -->
  <el-form
    ref="addOrEditFormRef"
    :model="formData"
    :rules="rules"
    label-width="180"
    style="height: 600px; overflow: auto; margin-bottom: 30px"
  >
    <!-- 项目基础信息 hzj 2023/11/6-->
    <el-row
      style="border-left: 5px solid #3b98f7; margin-left: 50px; text-indent: 2em; line-height: 30px; font-weight: 600"
      >项目基础信息 <el-text type="danger">项目监管单位会在行业分类以及项目所在地选择后自动加载可选项</el-text></el-row
    >
    <el-row justify="start" style="margin-top: 10px">
      <el-col :span="8">
        <el-form-item label="项目名称" prop="name">
          <el-input
            v-model="formData.name"
            :disabled="currentProject && currentProject.name != undefined && needDisable"
            placeholder="请输入项目名称"
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="项目编号" prop="prjNum">
          <el-input v-model="formData.prjNum" disabled placeholder="自动生成" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="建设性质" prop="propertyNum">
          <el-select
            v-model="formData.propertyNum"
            placeholder="请选择"
            :disabled="currentProject && currentProject.propertyNum != undefined && needDisable"
            clearable
          >
            <el-option v-for="item in projectPropertys" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="行业分类" prop="industryType">
          <el-select
            v-model="formData.industryType"
            placeholder="请选择行业分类"
            clearable
            :disabled="currentProject && currentProject.industryType != undefined && needDisable"
          >
            <el-option
              v-for="item in projectIndustryTypes"
              :key="item.value"
              :disabled="item.children.length == 0"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="项目分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择项目类型" clearable>
            <el-option v-for="item in projectCategorys" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="项目所在地" prop="areaCode">
          <el-cascader
            v-model="formData.areaCode"
            placeholder="请选择"
            :options="areaoptions"
            :disabled="
              currentProject && currentProject.areaCode != undefined && currentProject.areaCode != 0 && needDisable
            "
            @change="handleCascaderChange"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="项目监管单位" prop="deptId">
          <el-select v-model="formData.deptId" placeholder="请选择" clearable>
            <el-option v-for="item in deptList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="项目投资类别" prop="fundsSource">
          <el-select v-model="formData.fundsSource" placeholder="请选择" clearable>
            <el-option v-for="item in projectFundsSources" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item
          :label="formData.industryType == 1 ? '建筑市场监管平台编号' : '行业主管部门项目编号'"
          prop="industryPrjNum"
        >
          <el-input
            v-model="formData.industryPrjNum"
            :placeholder="formData.industryType == 1 ? '请输入建筑市场监管平台编号' : '请输入行业主管部门项目编号'"
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="是否有施工许可证" prop="isBuilderLicence">
          <el-radio-group v-model="formData.isBuilderLicence">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>

      <el-col v-if="formData.isBuilderLicence" :span="8">
        <el-form-item label="施工许可证编号" prop="builderLicences">
          <el-input v-model="formData.builderLicences" placeholder="请输入施工许可证编号" />
        </el-form-item>
      </el-col>
      <el-col v-if="formData.isBuilderLicence" :span="8">
        <el-form-item label="施工许可证发证日期" prop="builderLicencesGrantDate">
          <el-date-picker
            v-model="formData.builderLicencesGrantDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="formData.isBuilderLicence" :span="8">
        <el-form-item label="施工许可证有效期限" prop="builderLicencesTermDate">
          <el-date-picker
            v-model="formData.builderLicencesTermDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="中标合同价格(工程造价)" prop="contractAmount">
          <money-input
            v-model="formData.contractAmount"
            :disabled="currentProject && currentProject.contractAmount != undefined && needDisable"
            unit="万元"
          ></money-input>
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="合同开工日期" prop="contractStartDate">
          <el-date-picker
            v-model="formData.contractStartDate"
            :disabled="currentProject && currentProject.contractStartDate != undefined && needDisable"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
            @change="() => (formData.contractEndDate = undefined)"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="实际开工日期" prop="startDate">
          <el-date-picker
            v-model="formData.startDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="合同竣工日期" prop="contractEndDate">
          <el-date-picker
            v-model="formData.contractEndDate"
            :disabled="currentProject && currentProject.contractEndDate != undefined && needDisable"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledContractEndDate"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="总面积" prop="buildingArea">
          <el-input v-model="formData.buildingArea" type="number" placeholder="请输入总面积">
            <template #append>m²</template>
          </el-input>
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="总长度" prop="buildingLength">
          <el-input v-model="formData.buildingLength" type="number" placeholder="请输入总长度">
            <template #append>m</template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="中标通知书编号" prop="letterAcceptanceNum">
          <el-input v-model="formData.letterAcceptanceNum" placeholder="请输入中标通知书编号" />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="招标标段编号" prop="biddingSectionNum">
          <el-input
            v-model="formData.biddingSectionNum"
            :disabled="currentProject && currentProject.biddingSectionNum != undefined && needDisable"
            placeholder="请输入招标标段编号"
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="是否树立维权告示牌" prop="hasSafeGuardingBoard">
          <el-radio-group v-model="formData.hasSafeGuardingBoard">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="多地施工点位" prop="positionCount">
          <el-input-number v-model="formData.positionCount" :min="1" :max="12" placeholder="请输入多地施工点位" />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="联系人" prop="linkMan">
          <el-input v-model="formData.linkMan" placeholder="请输入联系人" />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="联系电话" prop="linkPhone">
          <el-input v-model="formData.linkPhone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-col>
      <el-col :span="22">
        <el-form-item label="项目地址" prop="address">
          <el-input
            v-model="formData.address"
            type="textarea"
            style="width: 100%"
            :row="1"
            placeholder="请输入项目地址"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="上传中标通知书/施工合同" prop="attachments">
          <el-upload
            v-model:file-list="fileList"
            :action="actionUrl"
            multiple
            :limit="5"
            accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
            :on-exceed="handleUploadExceed"
            :on-success="handleUploadSuccess"
            :on-preview="handleUploadPreview"
          >
            <el-button plain size="small">上传附件</el-button>
            <template #tip>
              <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col v-if="formData.positionCount > 1" :span="12">
        <el-form-item label="多地施工证明" prop="positionAttachments">
          <el-upload
            v-model:file-list="positionFileList"
            :action="actionUrl"
            multiple
            :limit="5"
            accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
            :on-exceed="handleUploadExceed"
            :on-success="handleUploadSuccess"
            :on-preview="handleUploadPreview"
          >
            <el-button plain size="small">上传附件</el-button>
            <template #tip>
              <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-col>

      <el-col :span="22">
        <el-form-item label="项目简介" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            style="width: 100%"
            :row="3"
            placeholder="请输入项目简介"
          />
        </el-form-item>
      </el-col>
      <el-col :span="2"> </el-col>
    </el-row>

    <!-- 参建单位信息 hzj 2023/11/6-->

    <el-row
      style="border-left: 5px solid #3b98f7; margin-left: 50px; text-indent: 2em; line-height: 30px; font-weight: 600"
      >参建单位信息
    </el-row>

    <el-row justify="start" style="margin-top: 10px">
      <el-col :span="8">
        <el-form-item label="建设单位" prop="buildCorpName">
          <el-select
            v-model="formData.buildCorpName"
            :disabled="currentProject && currentProject.buildCorpId != undefined && needDisable"
            filterable
            allow-create
            placeholder="请选择建设单位"
            @change="buildCorpChange"
          >
            <el-option
              v-for="item in constructors"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
          <el-text type="danger" style="white-space: nowrap"
            >建设单位信息可以手动输入也可以选择，若需要手动输入，则需要输入后在下拉选项中选择当前输入的信息</el-text
          >
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="建设单位信用代码" prop="buildCorpCode">
          <el-input
            v-model="formData.buildCorpCode"
            :disabled="constructors && constructors.find((i) => i.label == formData.buildCorpName)?.extend1"
            placeholder="请输入建设单位信用代码"
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="建设单位联系电话" prop="buildPhoneNum">
          <el-input v-model="formData.buildPhoneNum" placeholder="请输入建设单位联系电话" />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="选择建设单位指挥部" prop="commanderId">
          <el-select v-model="formData.commanderId" placeholder="请选择">
            <el-option v-for="item in commanders" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8"></el-col>
      <el-col :span="8"></el-col>
      <el-col :span="8" style="position: relative">
        <el-form-item label="监理企业" prop="supervisorCorpName">
          <el-select
            v-model="formData.supervisorCorpName"
            filterable
            allow-create
            clearable
            remote
            :loading="loadingSupervisor"
            :remote-method="remoteSupervisorMethod"
            placeholder="请点击选择监理企业"
            @change="buildJLCorpChange"
          >
            <el-option v-for="item in jlcorps" :key="item.name" :label="item.name" :value="item.name"></el-option>
          </el-select>
          <el-text type="danger" style="white-space: nowrap"
            >监理企业可以手动输入也可以选择，若需要手动输入，则需要输入后在下拉选项中选择当前输入的信息</el-text
          >
          <!-- <el-input
            v-model="formData.supervisorCorpName"
            readonly
            placeholder="请点击选择监理企业"
            @click="openJLCorpSelect"
          >
            <template #suffix>
              <CircleClose
                class="circle-close"
                style="width: 1em; height: 1em; margin-right: 0px; cursor: pointer"
                @click="jlCorpSendClose(undefined)"
              />
            </template>
          </el-input> -->
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="监理企业信用代码" prop="supervisorCorpCode">
          <el-input
            v-model="formData.supervisorCorpCode"
            placeholder="社会信用代码"
            :disabled="formData.supervisorCorpId > 0"
          />
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="监理企业合同金额" prop="supervisorCorpAmount">
          <money-input v-model="formData.supervisorCorpAmount" unit="万元"></money-input>
        </el-form-item>
      </el-col>
      <el-col v-if="!formData.hasSupervisor" :span="8">
        <el-form-item label="无监理说明" prop="supervisorContent">
          <el-input
            v-model="formData.supervisorContent"
            type="textarea"
            style="width: 100%"
            :row="3"
            placeholder="请描述无监理的情况"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="!formData.hasSupervisor" :span="24">
        <el-form-item label="无监理证明" prop="noSupervisorAttachments">
          <el-upload
            v-model:file-list="noSupervisorFileList"
            :action="actionUrl"
            multiple
            :limit="5"
            accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
            :on-exceed="handleUploadExceed"
            :on-success="handleUploadSuccess"
            :on-preview="handleUploadPreview"
          >
            <el-button plain size="small">上传附件</el-button>
            <template #tip>
              <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row
      style="border-left: 5px solid #3b98f7; margin-left: 50px; text-indent: 2em; line-height: 30px; font-weight: 600"
      >工程担保信息<el-text type="danger"
        >政府投资项目，担保单位可填写立项审批单位，附件请上传发改批复；社会投资项目请提供资金来源或担保函。</el-text
      >
    </el-row>
    <el-row justify="start" style="margin-top: 10px">
      <el-col :span="8">
        <el-form-item label="是否有工程款支付担保" prop="hasEarnestMoney">
          <el-radio-group v-model="formData.hasEarnestMoney">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col v-if="formData.hasEarnestMoney" :span="8">
        <el-form-item label="担保单位名称" prop="earnestUnitName">
          <el-input v-model="formData.earnestUnitName" placeholder="请输入担保单位名称" />
          <!-- <el-select v-model="formData.earnestUnitName" placeholder="请选择担保单位" @change="buildEarnestCorpChange">
            <el-option
              v-for="item in constructors"
              :key="item.label"
              filterable
              allow-create
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select> -->
        </el-form-item>
      </el-col>
      <el-col v-if="formData.hasEarnestMoney" :span="8">
        <el-form-item label="担保单位统一社会信用代码" prop="earnestUnitCode">
          <el-input v-model="formData.earnestUnitCode" placeholder="请输入统一社会信用代码" />
        </el-form-item>
      </el-col>
      <el-col v-if="formData.hasEarnestMoney" :span="8">
        <el-form-item label="担保金额" prop="earnestMoney">
          <money-input v-model="formData.earnestMoney" placeholder="请输入担保金额" unit="万元"></money-input>
        </el-form-item>
      </el-col>
      <el-col v-if="formData.hasEarnestMoney" :span="8">
        <el-form-item label="担保开始日期" prop="earnestStartDate">
          <el-date-picker
            v-model="formData.earnestStartDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
            @change="() => (formData.earnestEndDate = undefined)"
          />
        </el-form-item>
      </el-col>
      <el-col v-if="formData.hasEarnestMoney" :span="8">
        <el-form-item label="担保终止日期" prop="earnestEndDate">
          <el-date-picker
            v-model="formData.earnestEndDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
            :disabled-date="disabledEarnestEndDate"
          />
        </el-form-item>
      </el-col>

      <el-col v-if="formData.hasEarnestMoney" :span="24">
        <el-form-item label="上传担保文件" prop="earnestAttachments">
          <el-upload
            v-model:file-list="earnestFileList"
            :action="actionUrl"
            multiple
            :limit="5"
            accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
            :on-exceed="handleUploadExceed"
            :on-success="handleUploadSuccess"
            :on-preview="handleUploadPreview"
          >
            <el-button plain size="small">上传附件</el-button>
            <template #tip>
              <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script lang="ts" setup>
// 引入组件
import { get_register_form } from "@/api/account/project/index";
import { SearcChorps } from "@/api/common/corp/index";
import MoneyInput from "@/components/MoneyInput/index.vue";

import { CheckSocialCreditCode } from "@/utils/verify";
import { NewProjectManagerType } from "@/api/manager/project/types";
import { getDicts } from "@/store/modules/dict";
import { constructor_pulldown, getDeptPullDown, getCommanderPullDown } from "@/api/common/project";
import { FormItemRule, FormRules } from "element-plus/es/components/form/src/types";
import type { UploadUserFile } from "element-plus";
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);
import moment from "moment";
import { Except, Ride } from "@/utils/decimal";

//声明变量

const emit = defineEmits(["currentProject", "currentCorp"]);

//行政区划
const areaoptions = getDicts("areaTrees").filter((item: { value: number }) => item.value === 540000);
//项目行业主管部门
const projectIndustryTypes = getDicts("industryTypes");
//项目分类
const projectCategorys = ref();
// 项目种类
const projectFundsSources = getDicts("projectFundsSource");
//建设性质
const projectPropertys = getDicts("projectPropertys");

//当前项目登记选择的项目
const currentProject = ref<any>({});
const needDisable = ref<boolean>(false);

//监管单位(需要请求API获取)
const deptList = ref();
const jlcorps = ref<any[]>([]);
//上传文件列表
const fileList = ref<UploadUserFile[]>([]);
const positionFileList = ref<UploadUserFile[]>([]);
const noSupervisorFileList = ref<UploadUserFile[]>([]);
const earnestFileList = ref<UploadUserFile[]>([]);

//建设单位列表(需要请求API获取)
const constructors = ref();
//指挥部列表(需要请求API获取)
const commanders = ref();
const formData = reactive<NewProjectManagerType>({
  positionCount: 1,
  isBuilderLicence: false,
  isMultiConstruction: false,
  hasEarnestMoney: false,
  hasSupervisor: false,
  hasSafeGuardingBoard: false,
});
const addOrEditFormRef = ref(ElForm);
const loadingSupervisor = ref(false);

// old_getCorpList({ pageIndex: 1, pageSize: 99999 }).then((res: any) => {
//   if (res.success) {
//     jlcorps.value = res.data.list;
//   }
// });

//搜索企业
const remoteSupervisorMethod = (query: string) => {
  if (query.length > 1) {
    loadingSupervisor.value = true;
    SearcChorps(query).then((res: any) => {
      if (res.success) {
        jlcorps.value = res.data;
        loadingSupervisor.value = false;
      }
    });
  } else {
    jlcorps.value = [];
  }
};

/**
 * 禁用日期
 */
const disabledEarnestEndDate = (time: Date) => {
  if (formData.earnestStartDate) {
    return time.getTime() < moment(formData.earnestStartDate).toDate().getTime();
  }
};

//表单验证规则
const validatorAttachment = function (rule: any, value: any, callback: any) {
  if (fileList.value.length == 0) {
    callback(new Error("请上传附件!"));
  } else {
    callback();
  }
};

const validatorBuildingLength = function (rule: any, value: any, callback: any) {
  if (formData.isMultiConstruction && (formData.buildingLength ?? 0) < 10000) {
    callback(new Error("总长度必须大于10000米"));
  } else {
    callback();
  }
};
const validatorBuildingArea = function (rule: any, value: any, callback: any) {
  if (formData.isMultiConstruction && (formData.buildingArea ?? 0) < 10000) {
    callback(new Error("总面积必须大于10000平方米"));
  } else {
    callback();
  }
};

/* 统一社会信用代码检查 */
const SocialCreditCodeBlur = (rule: any, value: any, callback: any) => {
  if (!rule.required) {
    callback();
    return;
  }
  if (!value || value === undefined || value === "") {
    callback("请输入正确的统一社会信用代码");
    return;
  }
  if (value.length < 18) {
    callback("请输入正确的统一社会信用代码");
    return;
  }
  let check = CheckSocialCreditCode(value);
  if (check) {
    callback();
  } else {
    callback("请输入正确的统一社会信用代码");
  }
};
const validatorEarnestAttachment = function (rule: any, value: any, callback: any) {
  if (earnestFileList.value.length == 0) {
    callback(new Error("请上传担保文件附件!"));
    return;
  } else {
    callback();
  }
};
const rules = reactive<FormRules<NewProjectManagerType>>({
  lumpContractorCorpid: [{ required: true, message: "请选择施工总承包", trigger: "blur" }],
  lumpContractorCorpCode: [
    {
      required: true,
      message: "请输入施工总承包社会信用代码",
      trigger: "blur",
    },
  ],
  lumpContractorCorpPhoneNum: [{ required: true, message: "请输入施工总承包联系电话", trigger: "blur" }],
  name: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
  category: [{ required: true, message: "项目分类不能为空", trigger: "blur" }],
  propertyNum: [{ required: true, message: "建设性质不能为空", trigger: "blur" }],
  industryType: [{ required: true, message: "行业主管部门不能为空", trigger: "blur" }],
  fundsSource: [{ required: true, message: "项目种类不能为空", trigger: "blur" }],
  areaCode: [{ required: true, message: "项目归属地不能为空", trigger: "blur" }],
  address: [{ required: true, message: "项目地址不能为空", trigger: "blur" }],
  isBuilderLicence: [{ required: true, message: "请选择是否有建设许可证", trigger: "blur" }],
  builderLicences: [{ required: true, message: "施工许可证不能为空", trigger: "blur" }],
  builderLicencesGrantDate: [{ required: true, message: "施工许可证发证日期不能为空", trigger: "blur" }],
  builderLicencesTermDate: [{ required: true, message: "施工许可证有效期不能为空", trigger: "blur" }],
  contractAmount: [{ required: true, message: "中标合同金额不能为空", trigger: "blur" }],
  deptId: [{ required: true, message: "请选择项目监管单位", trigger: "change" }],
  contractStartDate: [{ required: true, message: "合同开工日期不能为空", trigger: "blur" }],
  contractEndDate: [{ required: true, message: "合同竣工日期不能为空", trigger: "blur" }],
  hasSafeGuardingBoard: [{ required: true, message: "请选择是否树立维权告示牌", trigger: "blur" }],
  positionCount: [{ required: true, message: "请输入多地施工点位", trigger: "blur" }],
  buildingLength: [
    {
      trigger: "blur",
      validator: validatorBuildingLength,
    },
    {
      trigger: "blur",
      validator(rule, value, callback, source, options) {
        if ((formData.buildingArea == undefined || formData.buildingArea == 0) && (value == undefined || value == 0)) {
          callback(new Error("总面积和总长度不能同时为空"));
        } else {
          callback();
        }
      },
    },
  ],
  buildingArea: [
    {
      trigger: "blur",
      validator: validatorBuildingArea,
    },
    {
      trigger: "blur",
      validator(rule, value, callback, source, options) {
        if (
          (formData.buildingLength == undefined || formData.buildingLength == 0) &&
          (value == undefined || value == 0)
        ) {
          callback(new Error("总面积和总长度不能同时为空"));
        } else {
          callback();
        }
      },
    },
  ],
  linkMan: [{ required: true, message: "联系人姓名不能为空", trigger: "blur" }],
  linkPhone: [
    { required: true, message: "联系人电话不能为空", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的电话号码",
      trigger: "blur",
    },
  ],
  attachments: [
    {
      required: true,
      message: "请上传项目文件",
      trigger: "blur",
      validator: validatorAttachment,
    },
  ],
  buildCorpName: [{ required: true, message: "建设单位名称不能为空", trigger: "blur" }],
  buildCorpCode: [{ required: true, trigger: "blur", validator: SocialCreditCodeBlur }],
  buildPhoneNum: [
    { required: false, message: "建设单位联系电话不能为空", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的电话号码",
      trigger: "blur",
    },
  ],
  positionAttachments: [
    {
      required: true,
      message: "请上传多地施工证明",
      trigger: "blur",
      validator(rule, value, callback, source, options) {
        if (positionFileList.value.length < 1) {
          callback(new Error("请上传多地施工证明"));
        } else {
          callback();
        }
      },
    },
  ],
  supervisorContent: [
    {
      required: true,
      message: "无监理说明不能为空",
      trigger: "blur",
    },
  ],
  noSupervisorAttachments: [
    {
      required: true,
      message: "请上传无监理证明",
      trigger: "blur",
      validator(rule, value, callback, source, options) {
        if (noSupervisorFileList.value.length < 1) {
          callback(new Error("请上传无监理证明"));
        } else {
          callback();
        }
      },
    },
  ],
  supervisorCorpId: [
    {
      trigger: "blur",
      validator(rule, value, callback, source, options) {
        if (
          formData.contractAmount != undefined &&
          formData.contractAmount > 400 &&
          (formData.supervisorCorpId == undefined ||
            formData.supervisorCorpId == null ||
            formData.supervisorCorpId == 0)
        ) {
          callback(new Error("合同金额大于400万元,请选择监理"));
        } else {
          callback();
        }
      },
    },
  ],
  supervisorCorpCode: [
    {
      required: false,
      trigger: "blur",
      validator: SocialCreditCodeBlur,
    },
  ],
  earnestUnitName: [{ required: true, message: "担保单位名称不能为空", trigger: "blur" }],
  earnestUnitCode: [
    { required: true, message: "担保单位统一社会信用编号不能为空", trigger: "blur", validator: SocialCreditCodeBlur },
  ],
  earnestMoney: [{ required: true, message: "担保金额不能为空", trigger: "blur" }],
  earnestStartDate: [{ required: true, message: "担保开始日期不能为空", trigger: "blur" }],
  earnestEndDate: [{ required: true, message: "担保终止日期不能为空", trigger: "blur" }],
  earnestAttachments: [
    {
      required: true,
      message: "请上传担保文件",
      trigger: "blur",
      validator: validatorEarnestAttachment,
    },
  ],
});

//选择监理企业
const buildJLCorpChange = function (val: any) {
  var info = jlcorps.value.find((i) => i.name == val);
  if (info) {
    formData.supervisorCorpAmount = 0;
    formData.supervisorCorpId = info.corpId;
    formData.supervisorCorpName = info.name;
    formData.supervisorCorpCode = info.code;
    formData.hasSupervisor = true;
  } else if (val != "" && val != null) {
    formData.supervisorCorpName = val;
    formData.supervisorCorpId = 0;
    formData.supervisorCorpCode = "";
    formData.supervisorCorpAmount = undefined;
    formData.hasSupervisor = true;
  } else {
    formData.supervisorCorpAmount = undefined;
    formData.supervisorCorpId = undefined;
    formData.supervisorCorpName = undefined;
    formData.supervisorCorpCode = undefined;
    formData.hasSupervisor = false;
  }
};
const isInit = ref(false);
//初始化表单数据
function initFormData() {
  emit("currentProject", (data: any, disable: boolean) => {
    needDisable.value = disable;
    if (data) {
      get_register_form(data).then((res) => {
        if (res.success) {
          if (res.data.deptId == 0) {
            res.data.deptId = undefined;
          }
          if (res.data.attachmentFiles) {
            let list = Array<any>();
            res.data.attachmentFiles.forEach((item: any) => {
              list.push({
                name: item.friendlyName,
                url: item.objectFilePath,
                status: "success",
                uid: item.id,
              });
            });
            fileList.value = list;
          }
          if (res.data.earnestAttachmentFiles) {
            let list = Array<any>();
            res.data.earnestAttachmentFiles.forEach((item: any) => {
              list.push({
                name: item.friendlyName,
                url: item.objectFilePath,
                status: "success",
                uid: item.id,
              });
            });
            earnestFileList.value = list;
          }
          if (res.data.positionAttachmentsFiles) {
            let list = Array<any>();
            res.data.positionAttachmentsFiles.forEach((item: any) => {
              list.push({
                name: item.friendlyName,
                url: item.objectFilePath,
                status: "success",
                uid: item.id,
              });
            });
            positionFileList.value = list;
          }
          if (res.data.noSupervisorAttachmentsFiles) {
            let list = Array<any>();
            res.data.noSupervisorAttachmentsFiles.forEach((item: any) => {
              list.push({
                name: item.friendlyName,
                url: item.objectFilePath,
                status: "success",
                uid: item.id,
              });
            });
            noSupervisorFileList.value = list;
          }
          console.log(res.data.contractAmount);
          if (res.data.contractAmount) res.data.contractAmount = Except(res.data.contractAmount, 10000);
          console.log(res.data.contractAmount);
          if (res.data.supervisorCorpAmount)
            res.data.supervisorCorpAmount = Except(res.data.supervisorCorpAmount, 10000);
          if (res.data.earnestMoney) res.data.earnestMoney = Except(res.data.earnestMoney, 10000);
          if (!res.data.earnestMoney) res.data.earnestMoney = Except(res.data.contractAmount, 10000);
          Object.assign(currentProject.value, res.data);
          Object.assign(formData, res.data);
          if (!res.data.hasEarnestMoney) {
            formData.hasEarnestMoney = false;
          }
          console.log(formData);
          projectCategorys.value =
            projectIndustryTypes.find((i: any) => i.value == formData.industryType)?.children ?? [];
          console.log(projectCategorys.value);
          if (res.data.areaCode && res.data.industryType) {
            initDeptPullDown();
          }
          if (res.data.buildCorpId) {
            initCommaderPullDown();
          }
        } else {
          ElMessage({
            type: "error",
            message: res.msg,
          });
          return;
        }
        setTimeout(() => {
          isInit.value = true;
        }, 2000);
      });

      return;
    }
    isInit.value = true;
  });
}

/*建设单位下拉框*/
constructor_pulldown().then((data) => {
  if (data.success) {
    constructors.value = data.data.list;
  } else {
    ElMessage({
      type: "error",
      message: data.msg,
    });
  }
});

/*监管单位下拉框*/
const initDeptPullDown = function () {
  getDeptPullDown({
    industryType: formData.industryType,
    areaCode: formData.areaCode,
  }).then((data) => {
    if (data.success) {
      deptList.value = data.data;
    } else {
      ElMessage({
        type: "error",
        message: data.msg,
      });
    }
  });
};

//页面加载完成
onMounted(() => {
  initFormData();
});

watch(
  () => formData.industryType,
  (curVal, preVal) => {
    if (curVal != preVal) {
      if (isInit.value) {
        formData.category = undefined;
      }
      projectCategorys.value = projectIndustryTypes.find((i: any) => i.value == formData.industryType)?.children ?? [];
    }
  }
);

//数据变化
watchEffect(() => {
  if (formData.areaCode && formData.industryType) {
    if (isInit.value) {
      formData.deptId = undefined;
    }
    initDeptPullDown();
  }
});

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

function buildCorpChange(val: string) {
  let temp = constructors.value.filter((item: { value: string }) => item.label === val);
  if (temp.length > 0) {
    formData.buildCorpName = temp[0].label;
    formData.buildCorpId = temp[0].value;
    formData.buildCorpCode = temp[0].extend1;
    initCommaderPullDown();
    return;
  } else if (val != "" && val != null) {
    formData.buildCorpName = val;
    formData.buildCorpId = 0;
    formData.buildCorpCode = "";
    commanders.value = [];
  } else {
    formData.buildCorpName = undefined;
    formData.buildCorpId = undefined;
    formData.buildCorpCode = undefined;
    commanders.value = [];
  }
}

/**
 * 禁用日期
 */
const disabledContractEndDate = (time: Date) => {
  if (formData.contractStartDate) {
    return time.getTime() < moment(formData.contractStartDate).toDate().getTime();
  }
};

//初始化指挥部下拉框
const initCommaderPullDown = function () {
  getCommanderPullDown(formData.buildCorpId).then((res) => {
    if (res.success) {
      commanders.value = res.data.list;
    } else {
    }
  });
};

//城市联动赋值
const handleCascaderChange = (value: any) => {
  if (value.length == 3) {
    formData.provinceCode = value[0];
    formData.cityCode = value[1];
    formData.areaCode = value[2];
  }
};
/**
 * 重置表单
 */
function resetForm() {
  initFormData();
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
}
/*表单校验*/
async function validation() {
  return await addOrEditFormRef.value.validate();
}

defineExpose({
  resetForm,
  validation,
  formData,
  fileList,
  noSupervisorFileList,
  positionFileList,
  earnestFileList,
});
</script>

<style lang="scss" scoped>
.d_left {
  margin-left: 60px;
}

:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 200px;
}

:deep(.el-input-number) {
  width: 200px;
}

:deep(.el-input__wrapper) {
  width: 200px;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}

// :deep(.el-upload__tip) {
//   display: inline-block;
//   margin-left: 10px;
// }
</style>
